package com.itheima.Controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.Bean.User;
import com.itheima.Service.UserService;
import com.itheima.Utils.SMSUtils;
import com.itheima.Utils.ValidateCodeUtils;
import com.itheima.common.R;
import com.itheima.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.lang.reflect.ParameterizedType;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("code={}",code);
//        SMSUtils.sendMessage("品优购","SMS_177538716",phone,code.toString());
        session.setAttribute(phone,code);
        return R.success(code.toString());
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map, HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");
        Object validateCode = session.getAttribute(phone);
        if(validateCode==null){throw new CustomException("验证码失效！"); }
        if(!validateCode.toString().equals(code)){throw new CustomException("验证码错误！"); }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);
        if(user==null){
            user = new User();
            user.setName("U_"+phone);
            user.setPhone(phone);
            userService.save(user);
        }
        session.setAttribute("userId",user.getId());
        return R.success("登录成功！");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("userId");
        return R.success("登录成功！");
    }

}
